package xj.graph2d.encoder;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import java.io.IOException;

import xj.graph2d.AbstractEncoder;
import xj.graph2d.DrawCanvas;
import xj.graph2d.View;

import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class ITextPDFEncoder extends AbstractEncoder {

  public ITextPDFEncoder() {
  }

  public ITextPDFEncoder(String name, String fileExtension,
      String fileDescription, View view) {
    super(name, fileExtension, fileDescription, view);
  }

  @Override
  public void encode(String filename, Rectangle2D r) throws IOException {
    if (view != null) {
      DrawCanvas canvas = view.getCanvas();
      if (filename != null && canvas != null && r != null) {
	int mw = (int) view.getMarginWidth();
	int mh = (int) view.getMarginHeight();
	int w = (int) r.getWidth() + 2 * mw;
	int h = (int) r.getHeight() + 2 * mw;

	try {

	  // step 1: creation of a document-object
	  com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(
	      w, h);
	  // pageSize.setBackgroundColor(new java.awt.Color(0xFF,
	  // 0xFF, 0xDE));
	  // Document document = new Document(pageSize);

	  com.lowagie.text.Document document = new com.lowagie.text.Document(
	      pageSize);

	  // step 2:
	  // we create a writer that listens to the document
	  // and directs a PDF-stream to a file
	  PdfWriter writer = PdfWriter.getInstance(document,
	      new FileOutputStream(filename));

	  // step 3: we open the document
	  document.open();

	  // step 4: we grab the ContentByte and do some stuff with it

	  // we create a fontMapper and read all the fonts in the font
	  // directory
	  DefaultFontMapper mapper = new DefaultFontMapper();
	  // mapper.insertDirectory("c:\\winnt\\fonts"); // ???

	  // we create a template and a Graphics2D object that
	  // corresponds with it
	  PdfContentByte cb = writer.getDirectContent();
	  PdfTemplate tp = cb.createTemplate(w, h);
	  Graphics2D g2 = tp.createGraphics(w, h, mapper);

	  if (!transparent) {
	    Color bg = view.getBackgroundColor();
	    g2.setColor(bg);
	    g2.fillRect(0, 0, w, h);
	  }

	  drawWaterMark(g2, 0, 0, w, h);

	  g2.translate(-r.getX() + mw, -r.getY() + mh);
	  view.paintCanvas(g2, null, true); // draw all objects

	  g2.dispose();
	  // cb.addTemplate(tp, mw, mh);
	  cb.addTemplate(tp, 0, 0);

	  // step 5: we close the document
	  document.close();
	} catch (com.lowagie.text.DocumentException de) {
	  System.err.println(de.getMessage());
	}

      }
    }
  }

}
